package com.haojie.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MyDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        //读取消息类型
        Short messageType = in.readShort();

        //支持REQUEST和RESPONSE
        if(messageType != MessageType.REQUEST.getCode() &&
                messageType != MessageType.RESPONSE.getCode()) {
            System.out.println("不支持此类数据");
            return;
        }

        //读取序列化的类型
        short serializerType = in.readShort();
        //得到序列化器
        Serializer serializer = Serializer.getSerializerByCode(serializerType);

        if(serializer == null) {
            throw new RuntimeException("不存在此序列化器");
        }

        //读取数据序列化后字节长度
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);

        //用相对应的序列化器解码字节数组
        Object deserialize = serializer.deserialize(bytes, messageType);
        out.add(deserialize);

    }
}
